package com.yjd.comm.util;

import java.io.StringWriter;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

/**
 * <b>description</b>：freemarker工具类 <br>
 * <b>time</b>：2014-12-18上午10:37:09 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class FreemarkerUtil {

	private static Configuration cfg = null;

	public static Configuration getCfg() throws TemplateException {
		if (cfg == null) {
			synchronized (FreemarkerUtil.class) {
				if (cfg == null) {
					cfg = new Configuration();
					cfg.setDefaultEncoding("UTF-8");
					cfg.setClassicCompatible(true);
					cfg.setTemplateUpdateDelay(10);
					// 设置模板文件所在的目录
					cfg.setClassForTemplateLoading(FreemarkerUtil.class,
							"/ftl/");
				}
			}
		}
		return cfg;
	}

	/**
	 * 
	 * 根据freemarker文件获取内容
	 * 
	 * @param ftlname
	 * @param rootMap
	 * @return
	 * @throws Exception
	 */
	public static String getFtlToString(String ftlname, Object rootMap)
			throws Exception {
		StringWriter sw = new StringWriter();
		getCfg().getTemplate(ftlname + ".ftl").process(rootMap,sw);
		return sw.toString();
	}

}
